package com.cy.es.repo;

import com.cy.es.entity.Student;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.elasticsearch.core.ElasticsearchOperations;
import org.springframework.data.elasticsearch.core.SearchHit;
import org.springframework.data.elasticsearch.core.SearchHits;
import org.springframework.data.elasticsearch.core.SearchOperations;
import org.springframework.data.elasticsearch.core.query.Criteria;
import org.springframework.data.elasticsearch.core.query.CriteriaQuery;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.stream.Collectors;

@Component
public class StuSearcher {

    @Autowired
    private ElasticsearchOperations op;

    // 按 birthDate 查询
    public List<Student> findByBirthDate(String birthDate){
        //用 Criteria 设置查询条件
        Criteria criteria = new Criteria("birthDate");
        criteria.is(birthDate);

        return search(criteria,null);
    }
    // 用 birthDate 的范围搜索
    public List<Student> findByBirthDate(String from,String to){
        Criteria criteria = new Criteria("birthDate");
        criteria.between(from,to);

        // 新建 Pageable实例设置分页参数
        PageRequest pageable = PageRequest.of(1, 1);

        return search(criteria,pageable);
    }

    //定义search方法
    private List<Student> search(Criteria criteria, Pageable pageable){
        //查询条件封装到Query对象
        CriteriaQuery query = new CriteriaQuery(criteria);

        //不是null值，才实现分页
        if (pageable != null){
            query.setPageable(pageable);
        }
        //执行搜索
        SearchHits<Student> hits = op.search(query, Student.class);
        //使用集合流操作简化
        List<Student> list = hits.stream().map(SearchHit::getContent).collect(Collectors.toList());

        return list;
    }
}
